<template>
  <div class="page">
    <el-card class="box-card" shadow="never">
      <MainGoBack :name="pageTitle">
        <template v-slot:right>
          <el-button class="add-btn" size="mini" @click="loadNews" v-if="pageControls !== 1">导入新闻</el-button>
        </template>
      </MainGoBack>
      <el-form ref="bannerFormRef" class="news-form" :model="formData" label-position="top" :rules="bannerAddRules" hide-required-asterisk :disabled="pageControls === 1">
        <el-form-item label="广告标题" prop="name">
          <template v-slot:label>
            <div class="news-form-label">
              <span></span>
              <p>广告标题</p>
              <el-checkbox v-model="formData.status" :true-label="1" :false-label="0">上架</el-checkbox>
            </div>
          </template>
          <el-input
            v-model.trim="formData.name"
            placeholder="广告标题"
            clearable
            :maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="广告图片" prop="cover">
          <template v-slot:label>
            <div class="news-form-label">
              <span></span>
              <p>广告图片</p>
            </div>
          </template>
          <p class="upload-tip">首张为主图，图片尺寸760*450px，大小≤6MB，支持JPG、PNG、JPEG</p>
          <el-upload
            class="avatar-uploader"
            :action="group_price_import"
            :on-success="handleAvatarSuccess"
            :limit="1"
            :file-list="imageUrl"
            list-type="picture-card"
            :before-upload="beforeAvatarUpload">
            <div class="uploader-wrap" v-if="!imageUrl.length">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </div>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="pageControls !== 1"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="开始/到期时间" :prop="formData.valid_status != 1 ? 'start_time' : ''">
          <template v-slot:label>
            <div class="news-form-label">
              <span></span>
              <p>开始/到期时间</p>
              <el-checkbox @change="validChange" v-model="formData.valid_status" :true-label="1" :false-label="0">永久有效</el-checkbox>
            </div>
          </template>
          <el-date-picker
            v-if="formData.valid_status != 1"
            v-model="formData.start_time"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发布时间" prop="publish_time">
          <template v-slot:label>
            <div class="news-form-label">
              <span></span>
              <p>发布时间</p>
            </div>
          </template>
          <el-date-picker
            v-model="formData.publish_time"
            type="datetime"
            placeholder="请选择发布时间"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="广告排序" prop="sort">
          <template v-slot:label>
            <div class="news-form-label">
              <span></span>
              <p>广告排序</p>
            </div>
          </template>
          <el-input v-model="formData.sort" placeholder="请输入1-50正整数广告排序" @input="handleInput"></el-input>
        </el-form-item>
        <el-form-item label="广告作者" prop="author">
          <template v-slot:label>
            <div class="news-form-label">
              <span></span>
              <p>广告作者</p>
            </div>
          </template>
          <el-input
            v-model.trim="formData.author"
            placeholder="广告作者"
            clearable
            :maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="广告简介" prop="intro">
          <template v-slot:label>
            <div class="news-form-label">
              <span></span>
              <p>广告简介</p>
            </div>
          </template>
          <el-input
            v-model.trim="formData.intro"
            placeholder="广告简介"
            clearable
            :maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="广告备注" prop="remark">
          <template v-slot:label>
            <div class="news-form-label">
              <span></span>
              <p>广告备注</p>
            </div>
          </template>
          <el-input
            v-model.trim="formData.remark"
            placeholder="广告备注"
            clearable
            :maxlength="30"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="广告内容" prop="info">
          <template v-slot:label>
            <div class="news-form-label">
              <span></span>
              <p>广告内容</p>
            </div>
          </template>
          <ueditor ref="ue" :content="formData.info"></ueditor>
        </el-form-item>
        <div class="bottom">
          <el-button
            class="btn"
            type="primary"
            @click="submit()"
            v-repeatClick
            >保存</el-button
          >
        </div>
      </el-form>
    </el-card>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <MainDialog
      title="导入新闻"
      :showDialog="loadNewsShow"
      width="1100px"
      @close="handleClose">
      <template v-slot:content>
        <MainSearchForm ref="newsFormRef" :formList="formList" :formValue="formValue" @formReset="formChange" @formSearch="formChange"></MainSearchForm>
        <div class="main_table">
          <MainTable
            ref="newsTable"
            :loading="listLoading"
            :columns="newsColumns"
            :tableData="tableData"
            showSelection
            @selection-change="handleSelectionChange"
            height="400"
          >
            <template v-slot:time="{ row }">
              <div>
                <p v-if="row.start_time">开始时间：{{ row.start_time }}</p>
                <p v-if="row.start_time">到期时间：{{ row.end_time }}</p>
                <p v-if="!row.start_time">永久上线</p>
              </div>
            </template>
          </MainTable>
        </div>
        <div class="flex mg-t-20">
          <MainPagination
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            background
            @size-change="changeSize"
            @current-change="changePage"
          />
        </div>
      </template>
      <template v-slot:footer>
        <div class="main-dialog-btn align-right">
          <el-button type="success" class="add-btn" @click="handleClose">取消</el-button>
          <el-button type="primary" class="submit" @click="handleLoad">确认发布</el-button>
        </div>
      </template>
    </MainDialog>
  </div>
</template>
<script>
import MainGoBack from '@/components/MainGoBack/goBack.vue'
import ueditor from "@/components/ueditor/myUeditor.vue";
import { Newsfromdata, group_price_import, getArticleDetails } from "@/api/news/index";
import { addBanner, getBannerDetail } from "@/api/news/banner";
import { getCategoryList } from "@/api/news/sort";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { bannerAddRules, indexData, bannerData } from '../MockData'
const { newsColumns } = bannerData
const { formList, formValue } = indexData
export default {
  data() {
    return {
      formData: {
        status: 1,
        name: '',
        start_time: '',
        sort: '',
        intro: '',
        info: '',
        valid_status: 0,
        cover: '',
        author: '',
        remark: '',
        link: '',
        publish_time: ''
      },
      imageUrl: [],
      group_price_import,
      bannerAddRules,
      dialogImageUrl: '',
      dialogVisible: false,
      categoryList: [],
      bannerId: null,
      loadNewsShow: false,
      formList,
      formValue,
      listLoading: false,
      currentPage: 1,
      pageSize: 20,
      tableData: [],
      total: 0,
      newsColumns,
      multipleSelection: null,
      pageControls: null  //  页面操作  空||0为新增，1为查看，2为编辑
    };
  },
  created() {
    this.pageControls = +this.$route.query.pageControls
    if(this.$route.query.id) {
      this.bannerId = this.$route.query.id
      this.getDetail()
    }
  },
  computed: {
    pageTitle() {
      return this.pageControls == 2 ? '编辑广告' : this.pageControls == 1 ? '查看广告' : '新增广告'
    }
  },
  methods: {
    handleInput(value) {
      // 替换掉非正整数的字符
      this.formData.sort = value.replace(/[^0-9]/g, '');
    },
    validChange(val) {
      if(val) {
        this.$refs.bannerFormRef.clearValidate('start_time')
      }
    },
    //  导入新闻
    loadNews() {
      this.loadNewsShow = !this.loadNewsShow
      if(this.loadNewsShow) {
        this.getNewsData()
        this.getCategory()
      }
    },
    //  获取分类列表
    getCategory() {
      const params = {
        page: this.currentPage,
        page_size: this.page_sizes,
        need_page: 0
      }
      getCategoryList(params).then(res => {
        this.formList[2].options = res.data.list.map(el => {
          return {
            label: el.name,
            value: el.id
          }
        })
      })
    },
    //  获取新闻详情
    getDetail() {
      getBannerDetail({ id: this.bannerId }).then(res => {
        console.log(res);
        this.formData = res.data.info
        this.formData.start_time = res.data.info.valid_status == 1 ? [] : [res.data.info.start_time, res.data.info.end_time]
        this.imageUrl.push({
          url: res.data.info.cover,
          name: res.data.info.cover
        })
      })
    },
    handleAvatarSuccess(res, file) {
      this.formData.cover = res.data.src
      this.imageUrl.push(file)
    },
    beforeAvatarUpload(file) {
      const isJPG = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 6;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG、PNG、JPEG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 6MB!');
      }
      return isJPG && isLt2M;
    },
    submit() {
      this.formData.info = this.$refs.ue.contents;
      const params = JSON.parse(JSON.stringify(this.formData))
      params.start_time = this.formData.valid_status == 1 ? '' : this.formData.start_time[0]
      params.end_time = this.formData.valid_status == 1 ? '' : this.formData.start_time[1]
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        params,
        { top: 0 }
      );
      this.$refs.bannerFormRef.validate((valid) => {
        if(valid) {
          const url = this.bannerId ? '/Article/banner-modify' : '/Article/banner-add'
          addBanner(url, data).then((res) => {
            if (res.errcode == 0) {
              this.$message.success(this.bannerId ? '修改成功' : "新增成功");
              setTimeout(() => {
                this.$router.push("/news/banner");
              }, 2000)
            } else {
              this.$message.error(res.errmsg);
            }
          });
        }
      })
      return 
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove() {
      this.imageUrl = []
      this.formData.cover = ''
    },
    handleClose() {
      this.$refs.newsFormRef.getFormRefs().resetFields()
      this.loadNewsShow = false
    },
    //  导入新闻
    async handleLoad() {
      this.loadNewsShow = false
      const { data } = await getArticleDetails({ id: this.multipleSelection[0].id })
      data.info.start_time = data.info.valid_status == 1 ? [] : [data.info.start_time, data.info.end_time]
      data.info.name = data.info.title
      delete data.info.title
      delete data.info.id
      delete data.info.top
      delete data.info.cate_id
      this.formData = data.info
      this.imageUrl = [{
        name: data.info.cover,
        url: data.info.cover
      }]
    },
    //  表单搜索
    formChange() {
      this.currentPage = 1
      this.pageSize = 20
      this.getNewsData()
    },
    getNewsData() {
      this.listLoading = true;
      let data = {
        page: this.currentPage,
        page_size: this.pageSize,
        ...this.formValue
      };
      let query = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, data)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        data,
      );
      Newsfromdata(query).then(
        (res) => {
          this.listLoading = false;
          this.tableData = res.data.list;
          this.total = res.data.total;
        },
        (err) => {
          console.log(err);
        }
      );
    },
    // 勾选的数据
    handleSelectionChange(val) {
      if(val.length > 1) {
        this.$refs.newsTable.getTableRef().clearSelection()
        this.$refs.newsTable.getTableRef().toggleRowSelection(val[val.length - 1], true)
        this.multipleSelection = val[val.length - 1];
      }else {
        this.multipleSelection = val;
      }
    },
    changePage(val) {
      this.currentPage = val;
      this.getNewsData()
    },
    changeSize(val) {
      this.pageSize = val;
      this.getNewsData()
    }
  },

  beforeDestroy() {
    // this.$bus.$off("Edit-row");
  },
  components: {
    ueditor,
    MainGoBack
  },
};
</script>

<style lang="scss" scoped>
.page {
  width: 100%;
  .bottom {
    background: #fff;
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    padding: 40px 0;
    .btn {
      width: 120px;
    }
  }
  .box-card {
    width: 100%;
    margin: 0.875rem;
    .news-form {
      width: 50%;
      .news-form-label {
        @include flex(flex-start, center);
        span {
          width: 10px;
          height: 10px;
          border-radius: 50%;
          background-color: $menuActiveText;
          margin-right: 10px;
        }
        p {
          font-size: $font_14;
          color: #333333;
          font-weight: bold;
          margin-right: 30px;
        }
      }
      /deep/.el-upload--picture-card {
        all: unset;
      }
      .avatar-uploader {
        height: 120px;
        position: relative;
      }
      .uploader-wrap {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        width: 120px;
        height: 120px;
        text-align: center;
        line-height: 120px;
        position: absolute;
        top: 0;
        &:hover {
          cursor: pointer;
          border-color: #409EFF;
        }
      }
      .avatar {
        width: 120px;
        height: 120px;
        display: block;
      }
      .upload-tip {
        color: #666666;
        font-size: $font_14;
        margin-bottom: 20px;
      }
    }
  }
  .el-select {
    width: 100%;
  }
  .el-date-editor {
    width: 100%;
    /deep/.el-range-input {
      width: 140px;
    }
  }
  .add-btn {
    padding: 6px 10px;
  }
  .mg-t-13 {
    margin-top: 13px;
  }
  .flex {
    @include flex(flex-end, center);
    margin-bottom: 14px;
  }
}
</style>